#!/bin/bash
expire_minute=10
sleep_sec=8
media_file_home="/data34/"
manifile="/data/proxy_cache_dir/cuclive/livestream/manifest.f4m"
urlbase="http://l2.cuctv.com/cuclive/livestream"
parse_urlbase="http://192.168.233.128:8383/cuclive/livestream"

echo "starting `date +"%F %T"`"

if [ ! -e $media_file_home ] ; then
   mkdir $media_file_home
fi

#http://192.168.233.128/cuclive/livestream/media_b125000_w2091662836.abst/Seg1-Frag19126
while [ ! -e $manifile  ] 
do
  echo "the file $manifile is not exists, just wait 1 second";
  sleep 1
done

playlist=`cat $manifile   |  grep "bootstrapInfo"  | awk   -F\"  '{print $4}'`
medialist=`cat $manifile  |  grep "<media"         | awk   -F\"  '{print $2}'`
url_playlist="$parse_urlbase/$playlist"
url_medialist="$urlbase/$medialist"
local_media_file="$media_file_home$medialist"
echo $url_playlist $url_medialist $local_media_file

if [ ! -e $local_media_file ] ; then
  mkdir $local_media_file
fi

frags=`curl -s "$url_playlist"`
echo $frags

if [ $frags != "repeated" -a $frags != "error" ] ; then
  echo "todownload segs"
  f=`echo $frags | sed  's/,/ /g'`
  for i in  $f ; do
    u="$url_medialist""Seg1-Frag"$i
    l="$local_media_file""Seg1-Frag"$i
    if [ ! -e $l ] ; then
      echo "download "$u
      curl -s $u  -o  $l
    else
      echo "has downloaded $u -> $l exists" 
    fi
  done 
fi

echo "delete expired file (exceed $expire_minute minute)"
find  $media_file_home -type f -cmin +$expire_minute 
find  $media_file_home -type f -cmin +$expire_minute  -exec rm -rf   {} \; 
echo "end `date +"%F %T"`"

cmd=$0
p=${cmd:0:1}
if [ "$p" = "." ] ; then
  curpath=`pwd`
  echo "$curpath/${cmd:2} sleep $sleep_sec(s)"
  echo  -e "\n\n\n\n"
  sleep $sleep_sec
  exec "$curpath/${cmd:2}"
#elif [ "$p" = "/" ] ; then
else
  echo "$0 sleep $sleep_sec(s)"
  echo  -e "\n\n\n\n"
  sleep $sleep_sec
  exec $0
fi

